package com.wzy.netty.nio.demo;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 描述  : NIO实现 socket通信 ,服务端
 * 创建人:    Wzy
 * 创建时间: 2020-06-10  17:16
 */
public class NIOServer {
    public static void main(String[] args) throws Exception {
        //获取服务端
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        //获取selector
        Selector selector = Selector.open();
        //绑定端口
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));

        //设置非阻塞
        serverSocketChannel.configureBlocking(false);

        //注册serverSocketChannel 到 selector
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //循环等待客户端连接
        while (true) {
            if (selector.select(1000) == 0) {
                System.out.println("没有事件发生");
                continue;
            }
            //如果返回的>0,直接获取所有的有关注事件发生的selectedKeys,可以反向获取所有注册的通道
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                //根据key对应的通道发生的事件做相应的处理
                if (key.isAcceptable()) {//如果是 客户端连接事件
                    //给该连接 生成socketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    System.out.println("客户端连接成功,生成了一个socketChannel," + socketChannel.hashCode());


                    //将socketChannel 注册到selector , 关注事件为OP_Read,同时给SocketChannel关联一个buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));

                }
                if (key.isReadable()) { // 如果通道里发生了可读取的事件
                    //通过 key 反向获取channel
                    SocketChannel channel = (SocketChannel) key.channel();

                    //获取到该channel关联的buffer,固定方法  通过key获取绑定过得buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    System.out.println("form 客户端:" + new String(buffer.array()).trim());
                }
                //手动从集合中删除已经处理的SelectionKey
                iterator.remove();
            }
        }
    }

}
